<?php
class Admin_Model_Mapper_User{
	protected $_dbTable;
 
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }
 
    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Admin_Model_DbTable_User');
        }
        return $this->_dbTable;
    }
		
	public function getPaginator($page, $itemsPerPage){	
		$paginator = Zend_Paginator::factory($this->getDbTable()->select());
		
		$paginator->setCurrentPageNumber($page);
		
		$paginator->setItemCountPerPage($itemsPerPage);

		$paginator->setPageRange(5);
		
		return $paginator; 
	}
	
	public function getPaginatorData($page, $itemsPerPage){
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->order("user_id desc")->limit($itemsPerPage, ($page-1) * $itemsPerPage));
		
		return $this->createResultSetEntity($resultSet);
	}
	
	public function find($userId, Admin_Model_User $user){
		$result = $this->getDbTable()->find($userId); 
		if (0 == count($result)){
			return;
		}				
		$row = $result->current();

        $user->setUserID($row->user_id)
                  ->setUserName($row->user_name)
                  ->setUserEmail($row->user_email)
				  ->setUserLoginName($row->user_loginname)
				  ->setUserPassword($row->user_password)
				  ->setUserLastActivity($row->user_last_activity)
				  ->setUserRole($row->user_role)
				  ->setUserIsActive($row->user_isactive);		
	}
	
	public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        
		return $this->createResultSetEntity($resultSet);
    }
	
	public function save(Admin_Model_User $user){			
		$data = array(
				"user_id" => $user->getUserID(),
				"user_name" => $user->getUserName(),
				"user_email" => $user->getUserEmail(),
				"user_loginname" =>$user->getUserLoginName(),
				"user_last_activity" => date("Y-m-d : H:i:s", time()), 
				"user_role" => $user->getUserRole(),
				"user_isactive" => $user->getUserIsActive()
        );
 
        if (null === ($userId = $user->getUserId())) {
            unset($data['user_id']);
			$data["user_password"] = base64_encode(md5($user->getUserPassword(), true));
            return $this->getDbTable()->insert($data);			
		}
		
		if ($user->getUserPassword() != ""){
			$data["user_password"] = base64_encode(md5($user->getUserPassword(), true));
		}

		return $this->getDbTable()->update($data, array('user_id = ?' => $userId));        
	}
		
	public function deleteUser($userId){					
		$users = $this->getDbTable()->find((int)$userId);
	
		$this->deleteSessionForUser($users[0]->user_loginname);
		$users[0]->delete();		
	}

	public function getAllUserActive(){
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->where(" user_isactive = 'Y' ")->order("user_id desc"));
        
		return $this->createResultSetEntity($resultSet);
	}
	
	public function getAllClientActive(){
		$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->where(" (user_role = '" . User_Model_DbTable_Users::USER_CLIENT . "' and user_isactive = 'Y') or (user_loginname = '" . $config->fmsadmin->username . "') ")->order("user_id desc"));
        
		return $this->createResultSetEntity($resultSet);
	}
	
	public function getUserByUserLoginName($userId, $userLoginName){
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->where("user_loginname ='$userLoginName' and not exists ( select user_id from User where user_id = $userId)")->order("user_id desc"));
            
		return $this->createResultSetEntity($resultSet);
	}
	
	public function getUserByUserEmail($userEmail, $userID){
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->where("user_email ='$userEmail' and user_id<> $userID")->order("user_id desc"));
        
		return $this->createResultSetEntity($resultSet);
	}
		
	public function isEqualWithDefaultAdmin($userName){
		$config = new Zend_Config_Ini( APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
			
		if(!isset($config->fmsadmin->username)){
			return false;
		}
	
		if($config->fmsadmin->username == $userName){
			return true;
		}
		
		return false;
	}
		
	private function createResultSetEntity($resultSet){
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Admin_Model_User();
			$entry->setUserId($row->user_id)
                  ->setUserName($row->user_name)
                  ->setUserEmail($row->user_email)
				  ->setUserLoginName($row->user_loginname)
				  ->setUserPassword($row->user_password)				  
				  ->setUserLastActivity($row->user_last_activity)
				  ->setUserRole($row->user_role)
				  ->setUserIsActive($row->user_isactive);
				
			$entries[] = $entry;
		}
		
		return $entries;
	}
	
	private function deleteSessionForUser($userLoginName){
		$sessionMapper = new User_Model_Mapper_Session();
		$listSession = $sessionMapper->fetchAll();
		$auth = Zend_Auth::getInstance();	
				
		$sessionHandler = Zend_Session::getSaveHandler();
		foreach($listSession as $session){
			$user = $this->unserializeSessionContainsUserInfo($session->Data);
			
			if(!isset($user["Zend_Auth"]["storage"])){
				continue;
			}
			
			if($user["Zend_Auth"]["storage"]->user_loginname == $auth->getIdentity()->user_name){
				Zend_Session::destroy();				
			}

			if($user["Zend_Auth"]["storage"]->user_loginname == $userLoginName){
				$sessionHandler->destroy($session->id);
			}
		}
	}
	
	private function unserializeSessionContainsUserInfo($data) {
        $vars = preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/', $data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        $numElements = count($vars);
        for($i=0; $numElements > $i && $vars[$i]; $i++) {
            $result[$vars[$i]]=unserialize($vars[++$i]);
        }
		
        return $result;
    }
}